<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

// 验证管理员权限（简化版）
function checkVerifierAuth() {
    global $auth;
    $user = $auth->getCurrentUser();
    if (!$user) {
        Response::authError('请先登录');
    }
    // 这里可以添加验证员权限检查
    return $user;
}

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'verify_code':
                // 验证预约码
                $reservationCode = $_GET['code'] ?? '';
                if (empty($reservationCode)) {
                    Response::error('缺少预约码');
                }
                
                $reservation = $db->fetchOne("
                    SELECT r.*, ts.slot_name, ts.start_time, ts.end_time, u.nickname,
                           (SELECT COUNT(*) FROM reservation_companions WHERE reservation_id = r.id) as companion_count
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    LEFT JOIN users u ON r.user_id = u.id
                    WHERE r.reservation_code = ? AND r.status IN ('confirmed', 'pending')
                ", [$reservationCode]);
                
                if (!$reservation) {
                    Response::error('无效的预约码或预约已取消');
                }
                
                // 检查预约是否过期
                $visitDate = $reservation['visit_date'];
                $today = date('Y-m-d');
                
                if ($visitDate < $today) {
                    // 更新过期状态
                    $db->update('reservations', [
                        'status' => 'expired',
                        'updated_at' => date('Y-m-d H:i:s')
                    ], 'id = :id', ['id' => $reservation['id']]);
                    
                    Response::error('预约已过期');
                }
                
                if ($visitDate > $today) {
                    Response::error('预约日期未到，参观日期：' . $visitDate);
                }
                
                // 检查时段是否匹配
                $currentTime = date('H:i:s');
                $startTime = $reservation['start_time'];
                $endTime = $reservation['end_time'];
                
                if ($startTime && $currentTime < $startTime) {
                    Response::error('尚未到预约时段，预约时间：' . $startTime . '-' . $endTime);
                }
                
                if ($endTime && $currentTime > $endTime) {
                    Response::error('预约时段已过，预约时间：' . $startTime . '-' . $endTime);
                }
                
                // 获取同伴信息
                $companions = $db->fetchAll("
                    SELECT * FROM reservation_companions WHERE reservation_id = ?
                ", [$reservation['id']]);
                
                $reservation['companions'] = $companions;
                $reservation['is_valid'] = true;
                $reservation['check_in_allowed'] = $reservation['check_in_time'] === null;
                
                Response::success($reservation, '预约码验证成功');
                break;
                
            case 'daily_statistics':
                // 获取当日统计
                $date = $_GET['date'] ?? date('Y-m-d');
                
                $stats = $db->fetchAll("
                    SELECT 
                        ts.slot_name,
                        ts.start_time,
                        ts.end_time,
                        rs.reserved_count,
                        rs.checked_in_count,
                        rs.cancelled_count,
                        (ts.max_visitors - COALESCE(rs.reserved_count, 0)) as available_count
                    FROM museum_time_slots ts
                    LEFT JOIN reservation_statistics rs ON ts.id = rs.time_slot_id AND rs.visit_date = ?
                    WHERE ts.is_active = 1
                    ORDER BY ts.sort_order
                ", [$date]);
                
                $totalStats = $db->fetchOne("
                    SELECT 
                        SUM(CASE WHEN status IN ('pending', 'confirmed') THEN visitor_count ELSE 0 END) as total_reserved,
                        SUM(CASE WHEN check_in_time IS NOT NULL THEN visitor_count ELSE 0 END) as total_checked_in,
                        SUM(CASE WHEN status = 'cancelled' THEN visitor_count ELSE 0 END) as total_cancelled
                    FROM reservations 
                    WHERE visit_date = ?
                ", [$date]);
                
                Response::success([
                    'date' => $date,
                    'slot_stats' => $stats,
                    'total_stats' => $totalStats
                ], '获取成功');
                break;
                
            case 'recent_checkins':
                // 获取最近签到记录
                $limit = (int)($_GET['limit'] ?? 20);
                $date = $_GET['date'] ?? date('Y-m-d');
                
                $checkins = $db->fetchAll("
                    SELECT r.*, ts.slot_name, u.nickname
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    LEFT JOIN users u ON r.user_id = u.id
                    WHERE DATE(r.check_in_time) = ? 
                    ORDER BY r.check_in_time DESC
                    LIMIT ?
                ", [$date, $limit]);
                
                Response::success($checkins, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        $verifier = checkVerifierAuth();
        
        switch ($action) {
            case 'check_in':
                // 签到
                if (!isset($input['reservation_code'])) {
                    Response::error('缺少预约码');
                }
                
                $reservationCode = $input['reservation_code'];
                $notes = $input['notes'] ?? '';
                
                $reservation = $db->fetchOne("
                    SELECT * FROM reservations 
                    WHERE reservation_code = ? AND status IN ('confirmed', 'pending')
                ", [$reservationCode]);
                
                if (!$reservation) {
                    Response::error('无效的预约码或预约已取消');
                }
                
                // 检查是否已签到
                if ($reservation['check_in_time']) {
                    Response::error('该预约已完成签到，签到时间：' . $reservation['check_in_time']);
                }
                
                // 执行签到
                $result = $db->update('reservations', [
                    'check_in_time' => date('Y-m-d H:i:s'),
                    'status' => 'completed',
                    'notes' => $reservation['notes'] . ($notes ? "\n[签到备注] " . $notes : ''),
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $reservation['id']]);
                
                if ($result) {
                    // 更新统计
                    updateReservationStatistics($reservation['visit_date'], $reservation['time_slot_id']);
                    
                    Response::success([
                        'reservation_id' => $reservation['id'],
                        'visitor_name' => $reservation['visitor_name'],
                        'visitor_count' => $reservation['visitor_count'],
                        'check_in_time' => date('Y-m-d H:i:s')
                    ], '签到成功');
                } else {
                    Response::error('签到失败');
                }
                break;
                
            case 'batch_check_in':
                // 批量签到
                if (!isset($input['reservation_codes']) || !is_array($input['reservation_codes'])) {
                    Response::error('缺少预约码列表');
                }
                
                $codes = $input['reservation_codes'];
                $notes = $input['notes'] ?? '';
                $results = [];
                $successCount = 0;
                
                try {
                    $db->getConnection()->beginTransaction();
                    
                    foreach ($codes as $code) {
                        $reservation = $db->fetchOne("
                            SELECT * FROM reservations 
                            WHERE reservation_code = ? AND status IN ('confirmed', 'pending')
                        ", [$code]);
                        
                        if (!$reservation) {
                            $results[] = ['code' => $code, 'success' => false, 'message' => '无效的预约码'];
                            continue;
                        }
                        
                        if ($reservation['check_in_time']) {
                            $results[] = ['code' => $code, 'success' => false, 'message' => '已签到'];
                            continue;
                        }
                        
                        $result = $db->update('reservations', [
                            'check_in_time' => date('Y-m-d H:i:s'),
                            'status' => 'completed',
                            'notes' => $reservation['notes'] . ($notes ? "\n[批量签到] " . $notes : ''),
                            'updated_at' => date('Y-m-d H:i:s')
                        ], 'id = :id', ['id' => $reservation['id']]);
                        
                        if ($result) {
                            $results[] = [
                                'code' => $code, 
                                'success' => true, 
                                'visitor_name' => $reservation['visitor_name'],
                                'visitor_count' => $reservation['visitor_count']
                            ];
                            $successCount++;
                        } else {
                            $results[] = ['code' => $code, 'success' => false, 'message' => '签到失败'];
                        }
                    }
                    
                    $db->getConnection()->commit();
                    
                    Response::success([
                        'total_count' => count($codes),
                        'success_count' => $successCount,
                        'results' => $results
                    ], "批量签到完成，成功 {$successCount} 个");
                    
                } catch (Exception $e) {
                    $db->getConnection()->rollBack();
                    Response::error('批量签到失败：' . $e->getMessage());
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}

// 更新预约统计的函数（复用）
function updateReservationStatistics($visitDate, $timeSlotId) {
    global $db;
    
    $stats = $db->fetchOne("
        SELECT 
            COUNT(CASE WHEN status IN ('pending', 'confirmed') THEN 1 END) as reserved_count,
            COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count,
            COUNT(CASE WHEN check_in_time IS NOT NULL THEN 1 END) as checked_in_count
        FROM reservations 
        WHERE visit_date = ? AND time_slot_id = ?
    ", [$visitDate, $timeSlotId]);
    
    $db->query("
        INSERT INTO reservation_statistics (visit_date, time_slot_id, reserved_count, cancelled_count, checked_in_count)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
        reserved_count = VALUES(reserved_count),
        cancelled_count = VALUES(cancelled_count),
        checked_in_count = VALUES(checked_in_count),
        updated_at = CURRENT_TIMESTAMP
    ", [
        $visitDate, 
        $timeSlotId, 
        $stats['reserved_count'], 
        $stats['cancelled_count'], 
        $stats['checked_in_count']
    ]);
}
?>